import threading

import redis


class RedisHelper:
    _instance_lock = threading.Lock()

    def __new__(cls, *args, **kwargs):
        if not hasattr(RedisHelper, "_instance"):
            with RedisHelper._instance_lock:
                if not hasattr(RedisHelper, "_instance"):
                    # 类加括号就回去执行__new__方法，__new__方法会创建一个类实例：Singleton()
                    RedisHelper._instance = object.__new__(cls, *args,
                                                           **kwargs)  # 继承object类的__new__方法，类去调用方法，说明是函数，要手动传cls
        return RedisHelper._instance  # obj1

    def __init__(self):
        self.pool = redis.ConnectionPool(host='47.106.112.136', port=6379, password="redis2018@", decode_responses=True)
        self.redis_obj = redis.Redis(connection_pool=self.pool)

    def set_string(self, key, value):
        self.redis_obj.set(key, value)

    def get_string(self, key, default_value):
        result = self.redis_obj.get(key)
        if result is None:
            return default_value
        return result

    def right_push(self, key, value):
        self.redis_obj.lpush(key, value)

    def left_pop(self, key):
        return self.redis_obj.lpop(key)

    def len_list(self, key):
        return self.redis_obj.llen(key)

    def index_list(self, key, index):
        return self.redis_obj.lindex(key, index)

    def list_remove(self, key, value):
        self.redis_obj.lrem(key, 0, value)

    def set(self, key, value, expire, nx):
        self.redis_obj.set(key, value, ex=expire, nx=nx)

    def register_script(self, script):
        self.redis_obj.register_script(script)
